import {Toast} from 'vant'
import _ from '@/utils/lodash'
let loading = null

function startLoading(){
  loading = Toast.loading({
    mask: true,
    message: '加载中...',
    duration: 0
  });
}

function endLoading(){
  loading.clear()
}

//那么 showFullScreenLoading() tryHideFullScreenLoading() 要干的事儿就是将同一时刻的请求合并。
//声明一个变量 needLoadingRequestCount，每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
//调用tryHideFullScreenLoading()方法，needLoadingRequestCount - 1。needLoadingRequestCount为 0 时，结束 loading。
let needLoadingRequestCount = 0
let loadingTimer;

function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
      startLoading()
  }
  needLoadingRequestCount++
}

function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  
  if (needLoadingRequestCount === 0) {
    _.debounce(tryCloseLoading, 300)()
  }
}

function tryCloseLoading() {
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}


export default {
  showFullScreenLoading:showFullScreenLoading,
  tryHideFullScreenLoading:tryHideFullScreenLoading
}
